import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';

typedef ListenerChange = List? Function();

/// 监听对应的值发生改变时才执行刷新
/// 为解决模型改变时 Obx 就会执行刷新的问题，
///
/// BaseObx(() => ImageView(
///                   imageUrl: state.roomModel.value?.roomBackgroundImg,
///                   clearMemoryCacheWhenDispose: true,
///                   fit: BoxFit.cover,
///                  ),
///          listenerChange: () =>[state.roomModel.value?.roomBackgroundImg],
/// );
///
class BaseObx extends Obx {
  final ListenerChange? listenerChange;

  BaseObx(super.builder, {super.key, this.listenerChange});

  Widget? _content;
  int? _listHashCode;

  @override
  Widget build() {
    if (listenerChange == null || (listenerChange!.call() ?? []).isEmpty) {
      clog("====> ${runtimeType.toString()} build child", tag: "obx");
      return builder.call();
    } else {
      int? code = jsonEncode(listenerChange!.call()).hashCode;
      if (code != _listHashCode) {
        clog("====> ${runtimeType.toString()} build child", tag: "obx");
        _content = builder.call();
        _listHashCode = code;
      }
      return _content ?? const SizedBox();
    }
  }
}
